package com.zc.mq;

import com.zc.service.BrokerMassageLogService;
import com.zc.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class RabbitOrderSender {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private BrokerMassageLogService brokerMassageLogService;

    public void send(RabbitOrder order) {

        /**
         * 设置生产者消息publish-confirm回调函数
         */
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {

            String massageId = correlationData.getId();
            if (ack) {
                //如果Confirm成功，将状态更新
                log.info("发送消息到交换器成功,MessageId:" + correlationData.getId());
                brokerMassageLogService.updataStatus(massageId, "1");//投递成功
            } else {
                //如果Confirm失败:重试或补偿手段等
                log.error("publishConfirm消息发送到交换器被退回，Id：", massageId, ";退回原因是：", cause);
                brokerMassageLogService.updataStatus(massageId, "2");//投递失败
            }
        });


        /**
         * 发送消息
         */
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(order.getMassageId());
        rabbitTemplate.convertAndSend("order-exchange",//交换机名称 exchange
                "order.abcd", //路由键
                order, //消息体内容
                correlationData);//消息唯一ID

    }

    public void sendSave(RabbitOrder order) {
        //记录发送消息
        brokerMassageLogService.creat(order.getMassageId(), JsonUtils.obj2string(order));
    }


}
